package fashionshop.dao;

import java.io.Serializable;

import org.apache.log4j.Logger;
import org.hibernate.Session;

import fashionshop.util.HibernateUtil;

public class CommonDao {
	
	private static final Logger LOGGER = Logger.getLogger(CommonDao.class);
	
	public Serializable saveEntity(Object entity){
		Session session = null;
		try{
			session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			Serializable rs = session.save(entity);
			session.getTransaction().commit();
			return rs;
		}catch(Exception ex){
			LOGGER.error("Save entity fail", ex);
			session.getTransaction().rollback();
			throw ex;
		}finally{
			session.close();
		}
	}
	
	public void updateEntity(Object entity){
		Session session = null;
		try{
			session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			session.update(entity);
			session.getTransaction().commit();
		}catch(Exception ex){
			LOGGER.error("Update entity fail", ex);
			session.getTransaction().rollback();
			throw ex;
		}finally{
			session.close();
		}
	}
	
	public Object getEntity(Class<?> clazz, Serializable id){
		Session session = null;
		try{
			session = HibernateUtil.getSessionFactory().openSession();
			return session.get(clazz, id);
		}catch(Exception ex){
			LOGGER.error("Get entity fail", ex);
			session.getTransaction().rollback();
			throw ex;
		}finally{
			session.close();
		}
	}

}
